package io.jft.doll.weidget

import android.content.Context
import android.support.v4.view.ViewCompat
import android.support.v4.widget.NestedScrollView
import android.support.v7.widget.RecyclerView
import android.util.AttributeSet
import android.view.View

/**
 * Created by G on 2018/1/12 0012.
 */
class RoomNestedScrollView : NestedScrollView {
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    private var isOnTop = false

    override fun onStartNestedScroll(child: View, target: View, nestedScrollAxes: Int): Boolean {
        isOnTop = target is RecyclerView && nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL && target.computeVerticalScrollOffset() <= 0
        return super.onStartNestedScroll(child, target, nestedScrollAxes)
    }

    override fun onStopNestedScroll(target: View) {
        isOnTop = false
        super.onStopNestedScroll(target)
    }

    override fun onNestedPreFling(target: View, velocityX: Float, velocityY: Float): Boolean {
        if (isOnTop && velocityY < 0 && target is RecyclerView) {
            fling(velocityY.toInt())
            return true
        }
        return super.onNestedPreFling(target, velocityX, velocityY)
    }
}